package belf.migrate.engine.job.jdbc;

import belf.migrate.engine.job.JobResult;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

import static belf.migrate.api.job.JobCode.*;

@Slf4j
public class JDBCJobManager {
    private Map<Long, JDBCJobRunner> jobs = new ConcurrentHashMap<Long, JDBCJobRunner>();  // jobId -> JDBCJobRunner

    private JDBCJobManager() {
    }

    // 利用类加载机制来实现线程安全和懒加载
    private static class JDBCJobManagerHolder {
        private static final JDBCJobManager INSTANCE = new JDBCJobManager();
    }

    // 单例
    public static JDBCJobManager getInstance() {
        return JDBCJobManagerHolder.INSTANCE;
    }

    public JobResult startJob(JDBCJobRunner jdbcJobRunner) {
        Long jobId = jdbcJobRunner.getJob().getJobId();
        if (jobs.containsKey(jobId)) {
            String errorMsg = String.format("JobId %d Exist.", jobId);
            log.error(errorMsg);
            return new JobResult(FAILTURE, errorMsg);
        }
        jobs.put(jobId, jdbcJobRunner);
        return new JobResult(SUCCESS, String.format("JobId %d Created.", jobId));
    }

    public void stopJob(long jobId) {
        JDBCJobRunner jdbcJobRunner = jobs.get(jobId);
        if (Objects.nonNull(jdbcJobRunner)) {
            jdbcJobRunner.shutdown();
            jobs.remove(jobId);
        }
    }
}
